/*
 * 处理空字符为 undefined
 * 处理'boolean'为boolean
 * 处理'null'为null
 * 处理'undefined'为undefined
 */
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common'
import { Observable } from 'rxjs'

@Injectable()
export class TransformEmptyStringInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const request = context.switchToHttp().getRequest()

    // 处理 query 参数
    if (request.query) {
      request.query = this.transformObject(request.query)
    }

    // ✅ 如果你想也清洗 params：
    if (request.params) {
      request.params = this.transformObject(request.params)
    }

    // ✅ 如果你想清洗 body 也可以启用：
    if (request.body) {
      request.body = this.transformObject(request.body)
    }

    return next.handle()
  }

  private transformObject(obj: any): any {
    if (obj === null || obj === undefined)
      return obj

    if (Array.isArray(obj)) {
      return obj.map(item => this.transformObject(item))
    }

    if (typeof obj === 'object') {
      const result: any = {}
      for (const key in obj) {
        if (!Object.prototype.hasOwnProperty.call(obj, key))
          continue
        result[key] = this.transformValue(obj[key])
      }
      return result
    }

    return this.transformValue(obj)
  }

  private transformValue(value: any): any {
    if (value === '')
      return undefined
    if (value === 'true')
      return true
    if (value === 'false')
      return false
    if (value === 'null')
      return null
    if (value === 'undefined')
      return undefined

    if (typeof value === 'object')
      return this.transformObject(value)
    return value
  }
}
